﻿using Dapper;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using OMG.Fill.Mulberry.Model;
using OMG.Fill.Mulberry.Model.Ent;
using ProjectShare;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace OMG.Fill.Mulberry.Service
{
    /// <summary>
    /// 表4全年饲养蚕品种构成调查表T_MulAnnualRear通用操作类
    /// </summary>
    public class MulAnnualRearServices : MulAnnualRears
    {
        DictServices dict = new DictServices();
        ReportServices reportServices = new ReportServices();
        public Pager<List<MulAnnualRearEntity>> GetPageList(MulAnnualRearQuery query)
        {
            Pager<List<MulAnnualRearEntity>> obj = new Pager<List<MulAnnualRearEntity>>();
            var paramlist = new DynamicParameters();
            string strWhereSql = "";//from 表在下面，需完善其他查询条件在这里接的写，格式为："and xxx=@xxx空格,如下注释部分代码所示："
            //if (!string.IsNullOrEmpty(query.GroupCode))
            //{
            //  strWhereSql += "and GroupCode = @GroupCode ";
            //  paramlist.Add("GroupCode", query.GroupCode);
            //}
            string strFromSql = "from dbo.T_MulAnnualRear where 1=1 " + strWhereSql;
            string strTotal = "select count(1)" + strFromSql + strWhereSql;
            string strOrderSql = "";//自定义完成order by语句
            string strSql = @"select * from (select *,ROW_NUMBER() over (order by Id ) as RowNumber " + strFromSql + ") as t ";
            strSql += "where t.RowNumber between  @minRow and @maxRow" + strOrderSql;
            paramlist.Add("minRow", query.MinRow);
            paramlist.Add("maxRow", query.MaxRow);
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    obj.rows = dbCon.Query<MulAnnualRearEntity>(strSql, paramlist).ToList();
                    obj.total = dbCon.Query<int>(strTotal, paramlist).FirstOrDefault();
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "获取成功！";
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("获取表4全年饲养蚕品种构成调查表T_MulAnnualRear分页列表失败", ex);
                return obj;
            }
        }
        /// <summary>
        /// 获取指定对象
        /// </summary>
        public ResResult<List<MulAnnualRearEntity>> GetList(string ReportId)
        {
            ResResult<List<MulAnnualRearEntity>> obj = new ResResult<List<MulAnnualRearEntity>>();
            MulAnnualRearEntity model = new MulAnnualRearEntity();
            if (CheckRepCount(ReportId))
            {
                model.ReportId = ReportId;
                model.CultivarName = "";
                model.Remark = "";
                if (AddInfo(model).status > 0)
                {
                    obj.model = new List<MulAnnualRearEntity>();
                    obj.model.Add(model);
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "获取成功！";
                }
            }
            else
            {
                string strSql = @"select * from dbo.T_MulAnnualRear where ReportId = @ReportId";
                try
                {
                    using (var dbCon = ConnectFactory.GetOpenConnection())
                    {
                        obj.model = dbCon.Query<MulAnnualRearEntity>(strSql, new { ReportId = ReportId }).ToList();
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "获取成功！";
                        dbCon.Dispose();//数据库连接释放
                    }
                }
                catch (Exception ex)
                {
                    obj.status = DefaultKey.ErrorResult;
                    obj.message = ex.ToString().Trim();
                    LogHelper.ErrorLog("获取表1桑园面积统计表T_MulAnnualRear对象信息失败", ex);

                }
            }
            return obj;
        }
        /// <summary>
        /// 判定是否生成过报表
        /// </summary>
        /// <param name="reportId"></param>
        /// <returns>没生成过true,否则false</returns>
        public bool CheckRepCount(string reportId)
        {
            string strSql = @"select count(1) from dbo.T_MulAnnualRear where ReportId=@ReportId";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    //为0，没生成过true,否则false
                    return dbCon.Query<int>(strSql, new { ReportId = reportId }).FirstOrDefault() == 0 ? true : false;
                }
            }
            catch (Exception ex)
            {
                LogHelper.ErrorLog("判断是否生成过表1桑园面积统计表T_MulAnnualRear失败", ex);
                return false;
            }
        }
        public ResResult<int> AddInfo(List<MulAnnualRearEntity> list)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"INSERT INTO dbo.T_MulAnnualRear";
            strSql += "(";
            strSql += "Id,";
            strSql += "ReportId,";
            strSql += "CultivarName,";
            strSql += "SeedSizeSpring,";
            strSql += "SeedSizeSummer,";
            strSql += "SeedSizeAutumn,";
            strSql += "Remark,SeedSizeZQ,SeedSizeWQ)";
            strSql += " values(";
            strSql += "@Id,";
            strSql += "@ReportId,";
            strSql += "@CultivarName,";
            strSql += "@SeedSizeSpring,";
            strSql += "@SeedSizeSummer,";
            strSql += "@SeedSizeAutumn,";
            strSql += "@Remark,@SeedSizeZQ,@SeedSizeWQ)";
            using (var dbCon = ConnectFactory.GetOpenConnection())
            {
                var trans = dbCon.BeginTransaction();
                try
                {
                    for (int i = 0; i < list.Count; i++)
                    {
                        list[i].Id = CustomFun.GetGuid();
                    }
                    
                    string strDel = "delete from dbo.T_MulAnnualRear where ReportId=@ReportId";
                    dbCon.Execute(strDel, new { ReportId = list[0].ReportId}, trans);
                    int result = dbCon.Execute(strSql, list, trans);
                    string strRep = "update dbo.T_Report set Status='2',UpdateTime=@UpdateTime where Id=@ReportId";
                    dbCon.Execute(strRep, new { ReportId = list[0].ReportId, UpdateTime = DateTime.Now }, trans);
                    //提交事务
                    trans.Commit();
                    obj.model = result;
                    obj.status = DefaultKey.SuccessResult;
                    obj.message = "更新成功！";
                    dbCon.Dispose();//数据库连接释放
                    return obj;

                }
                catch (Exception ex)
                {
                    obj.status = DefaultKey.ErrorResult;
                    obj.message = ex.ToString().Trim();
                    LogHelper.ErrorLog("新增表4全年饲养蚕品种构成调查表T_MulAnnualRear对象信息失败", ex);
                    return obj;
                }
            }
        }

        /// <summary>
        /// 读取导入的Excel数据
        /// </summary>
        /// <param name="pathName">导入文件路径</param>
        /// <param name="fileSuffix">文件后缀</param>
        /// <param name="sheetName">sheet名称</param>
        /// <param name="startRow">从第几行开始读取数据</param>
        /// <returns></returns>
        public List<MulAnnualRearInfoModel> ExcelToModel(string pathName, string fileSuffix, string sheetName, int startRow)
        {

            IWorkbook workbook = null;
            ISheet sheet = null;
            List<MulAnnualRearInfoModel> list = new List<MulAnnualRearInfoModel>();
            FileStream fs = new FileStream(pathName, FileMode.Open, FileAccess.Read);
            switch (fileSuffix)
            {
                case ".xls":
                    workbook = new HSSFWorkbook(fs);
                    break;
                case ".xlsx":
                    workbook = new XSSFWorkbook(fs);
                    break;
                default:
                    workbook = new HSSFWorkbook(fs);
                    break;
            }
            if (!string.IsNullOrEmpty(sheetName))
            {
                sheet = workbook.GetSheet(sheetName);
                if (sheet == null) //如果没有找到指定的sheetName对应的sheet，则尝试获取第一个sheet
                {
                    sheet = workbook.GetSheetAt(0);
                }
            }
            else
            {
                sheet = workbook.GetSheetAt(0);
            }
            if (sheet != null)
            {
                //获取有数据的行数
                int rowCount = 0;
                for (int i = startRow; i <= sheet.LastRowNum; i++)
                {
                    IRow row = sheet.GetRow(i);
                    if (row != null)
                    {
                        rowCount = sheet.GetRow(i).RowNum;
                    }
                    else
                    {
                        break;
                    }
                }
                for (int i = startRow; i <= rowCount; i++)
                {
                    IRow row = sheet.GetRow(i);
                    MulAnnualRearInfoModel model = new MulAnnualRearInfoModel();
                    if (row.GetCell(0) != null && row.GetCell(0).ToString() != "")
                    {
                        model.CultivarName = dict.GetPZKey(row.GetCell(0).ToString(), "CSCultivar");
                    }
                    else
                    {
                        model.CultivarName = null;
                    }
                    if (row.GetCell(1) != null && row.GetCell(1).ToString() != "")
                    {
                        model.SeedSizeSpring = decimal.Parse(row.GetCell(1).ToString());
                    }
                    else
                    {
                        model.SeedSizeSpring = null;
                    }
                    if (row.GetCell(2) != null && row.GetCell(2).ToString() != "")
                    {
                        model.SeedSizeSummer = decimal.Parse(row.GetCell(2).ToString());
                    }
                    else
                    {
                        model.SeedSizeSummer = null;
                    }
                    if (row.GetCell(3) != null && row.GetCell(3).ToString() != "")
                    {
                        model.SeedSizeZQ = decimal.Parse(row.GetCell(3).ToString());
                    }
                    else
                    {
                        model.SeedSizeZQ = null;
                    }
                    if (row.GetCell(4) != null && row.GetCell(4).ToString() != "")
                    {
                        model.SeedSizeWQ = decimal.Parse(row.GetCell(4).ToString());
                    }
                    else
                    {
                        model.SeedSizeWQ = null;
                    }
                    if (row.GetCell(5) != null && row.GetCell(5).ToString() != "")
                    {
                        model.Remark = row.GetCell(5).ToString();
                    }
                    else
                    {
                        model.Remark = null;
                    }
                    list.Add(model);
                }
            }
            return list;
        }

        /// <summary>
        /// 添加
        /// </summary>
        public virtual ResResult<int> AddInfo(List<MulAnnualRearInfoModel> model,string ReportId)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"INSERT INTO dbo.T_MulAnnualRear";
            strSql += "(";
            strSql += "Id,";
            strSql += "ReportId,";
            strSql += "CultivarName,";
            strSql += "SeedSizeSpring,";
            strSql += "SeedSizeSummer,";
            strSql += "SeedSizeAutumn,";
            strSql += "Remark,SeedSizeZQ,SeedSizeWQ)";
            strSql += " values(";
            strSql += "@Id,";
            strSql += "@ReportId,";
            strSql += "@CultivarName,";
            strSql += "@SeedSizeSpring,";
            strSql += "@SeedSizeSummer,";
            strSql += "@SeedSizeAutumn,";
            strSql += "@Remark,@SeedSizeZQ,@SeedSizeWQ)";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    for(int i=0;i<model.Count;i++)
                    {
                        model[i].ReportId = ReportId;
                        model[i].Id = CustomFun.GetGuid();
                    }
                   
                    int result = dbCon.Execute(strSql, model);
                    if (result > 0)
                    {
                        obj.model = result;
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "添加成功！";
                    }
                    else
                    {
                        obj.model = result;
                        obj.status = DefaultKey.InfoResult;
                        obj.message = "添加失败！数量为:" + result;
                    }
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("新增表4全年饲养蚕品种构成调查表T_MulAnnualRear对象信息失败", ex);
                return obj;
            }
        }
        /// <summary>
        /// 修改
        /// </summary>
        public virtual ResResult<int> UpdateInfo(MulAnnualRearInfoModel model)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"UPDATE dbo.T_MulAnnualRear set ";
            strSql += "CultivarName = @CultivarName,";
            strSql += "SeedSizeSpring = @SeedSizeSpring,";
            strSql += "SeedSizeSummer = @SeedSizeSummer,";
            strSql += "SeedSizeAutumn = @SeedSizeAutumn,";
            strSql += "Remark = @Remark,SeedSizeZQ=@SeedSizeZQ,SeedSizeWQ=@SeedSizeWQ";
            strSql += " where ReportId = @ReportId";
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    int result = dbCon.Execute(strSql, model);
                    if (result > 0)
                    {
                        obj.model = result;
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "更新成功！";
                    }
                    else
                    {
                        obj.model = result;
                        obj.status = DefaultKey.InfoResult;
                        obj.message = "更新失败！数量为:" + result;
                    }
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("更新表4全年饲养蚕品种构成调查表T_MulAnnualRear对象信息失败", ex);
                return obj;
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        public ResResult<int> DeleteData(string id)
        {
            ResResult<int> obj = new ResResult<int>();
            string strSql = @"delete from dbo.T_MulAnnualRear where ReportId = @Id";
            int result;
            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    result = dbCon.Execute(strSql, new { Id = id });
                    if (result > 0)
                    {
                        obj.model = result;
                        obj.status = DefaultKey.SuccessResult;
                        obj.message = "删除成功！";
                    }
                    else
                    {
                        obj.model = result;
                        obj.status = DefaultKey.InfoResult;
                        obj.message = "删除失败！数量为:" + result;
                    }
                    dbCon.Dispose();//数据库连接释放
                    return obj;
                }
            }
            catch (Exception ex)
            {
                obj.status = DefaultKey.ErrorResult;
                obj.message = ex.ToString().Trim();
                LogHelper.ErrorLog("删除表4全年饲养蚕品种构成调查表T_MulAnnualRear对象信息失败", ex);
                return obj;
            }
        }

        /// <summary>
        /// 饲养蚕品种构成统计--------(按年统计)
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResResult<List<MulAnnualRearStatsModel>> GetStatsList(MulNowModel model)
        {
            DictServices dictServices = new DictServices();
            string CultivarName = dict.GetPZName(model.itemText, "CSCultivar");//品种名称
            if (!string.IsNullOrEmpty(model.FillInYear))
            {
                model.FillInYear = dictServices.GetPZKey(model.FillInYear, "ReportYear");
            }

            string ProvinceCode = "530000000000";
            ResResult<List<MulAnnualRearStatsModel>> result = new ResResult<List<MulAnnualRearStatsModel>>();
            /*县级统计代码*/
            string StrAreaSql = "select DictText year,Area.Code AreaCode,Area.FullName AreaName,Coord";
            StrAreaSql += ",ISNULL(SeedSizeTotal,0.00) SeedSizeTotal,ISNULL(SeedSizeSpring,0.00) SeedSizeSpring";
            StrAreaSql += ",ISNULL(SeedSizeSummer,0.00) SeedSizeSummer, ISNULL(SeedSizeZQ,0.00) SeedSizeZQ,ISNULL(SeedSizeWQ,0)SeedSizeWQ ";
            StrAreaSql += " from(";
            StrAreaSql += "select ";
            StrAreaSql += "case when grouping(Area.Code) = 1 then @AreaCode else Code end Code, ";
            StrAreaSql += "SUM(ISNULL(MulAnnualRear.SeedSizeSpring,0.00)+ISNULL(MulAnnualRear.SeedSizeSummer,0.00)+ISNULL(MulAnnualRear.SeedSizeZQ,0.00)+ISNULL(MulAnnualRear.SeedSizeWQ,0.00))  SeedSizeTotal, ";//--现有面积
            StrAreaSql += "SUM(ISNULL(MulAnnualRear.SeedSizeSpring,0.00)) SeedSizeSpring, ";// --春季发种量
            StrAreaSql += "SUM(ISNULL(MulAnnualRear.SeedSizeSummer,0.00)) SeedSizeSummer, ";//--夏季量合计
            StrAreaSql += "SUM(ISNULL(MulAnnualRear.SeedSizeZQ,0.00))   SeedSizeZQ,  ";//--正秋季量合计
            StrAreaSql += "SUM(ISNULL(MulAnnualRear.SeedSizeWQ,0.00))   SeedSizeWQ  ";//--晚秋季量合计
            StrAreaSql += "from([dbo].[T_Report] Report left join T_MulAnnualRear MulAnnualRear on Report.Id = MulAnnualRear.ReportId) ";
            StrAreaSql += "right join T_Area Area on Area.Code = Report.AreaCode ";
            StrAreaSql += "where ";
            if (model.itemText == "" || model.itemText == null) {
                StrAreaSql += "Area.ParentCode = @AreaCode  and Report.Status=@ReportStatus and Report.FillInYear=@FillInYear ";
            }else
            {
                StrAreaSql += "Area.ParentCode = @AreaCode  and Report.Status=@ReportStatus and Report.FillInYear=@FillInYear and MulAnnualRear.CultivarName=@CultivarCode ";
            }
            StrAreaSql += "group by rollup(Area.Code)) tt1 left join T_Area Area on tt1.Code = Area.Code inner join T_Dict Dict  on Dict.GroupCode='ReportYear' and DictValue=@FillInYear ";
            StrAreaSql += "where area.ParentCode=@AreaCode  or area.Code=@AreaCode ";
            StrAreaSql += "order by AreaCode asc ";

            /*市级统计代码*/
            string StrCitySql = "select  Area.Code AreaCode,Dict.DictText year, Area.FullName AreaName, Coord ";
            StrCitySql += ",ISNULL(SeedSizeTotal,0.00) SeedSizeTotal,ISNULL(SeedSizeSpring,0.00) SeedSizeSpring";
            StrCitySql += ",ISNULL(SeedSizeSummer,0.00) SeedSizeSummer, ISNULL(SeedSizeZQ,0.00) SeedSizeZQ,ISNULL(SeedSizeWQ,0)SeedSizeWQ ";
            StrCitySql += "from( ";
            StrCitySql += "select ";
            StrCitySql += "case when grouping(Area.ParentCode) = 1 then @AreaCode else ParentCode end ParentCode, ";
            StrCitySql += "SUM(ISNULL(MulAnnualRear.SeedSizeSpring,0.00)+ISNULL(MulAnnualRear.SeedSizeSummer,0.00)+ISNULL(MulAnnualRear.SeedSizeZQ,0.00)+ISNULL(MulAnnualRear.SeedSizeWQ,0.00))  SeedSizeTotal, ";//--现有面积
            StrCitySql += "SUM(ISNULL(MulAnnualRear.SeedSizeSpring,0.00)) SeedSizeSpring, ";// --春季发种量
            StrCitySql += "SUM(ISNULL(MulAnnualRear.SeedSizeSummer,0.00)) SeedSizeSummer, ";//--夏季量合计
            StrCitySql += "SUM(ISNULL(MulAnnualRear.SeedSizeZQ,0.00))   SeedSizeZQ,  ";//--正秋季量合计
            StrCitySql += "SUM(ISNULL(MulAnnualRear.SeedSizeWQ,0.00))   SeedSizeWQ  ";//--晚秋季量合计
            StrCitySql += "from t_report t1  ";
            StrCitySql += "left  join T_MulAnnualRear MulAnnualRear on MulAnnualRear.ReportId = t1.Id  ";
            StrCitySql += "right  join T_Area Area on Area.Code = t1.AreaCode  ";
            if (model.itemText==""|| model.itemText==null) {
                StrCitySql += "where ParentCode!=@AreaCode  and t1.FillInYear=@FillInYear and t1.Status=@ReportStatus  ";
            }else
            {
                StrCitySql += "where ParentCode!=@AreaCode  and t1.FillInYear=@FillInYear and t1.Status=@ReportStatus and MulAnnualRear.CultivarName=@CultivarCode  ";
            }
            StrCitySql += "group by rollup(Area.ParentCode)  ";
            StrCitySql += ") t left join T_Area  area on area.Code = t.ParentCode  ";
            StrCitySql += "inner join T_Dict Dict  on Dict.GroupCode = 'ReportYear' and DictValue = @FillInYear  ";
            StrCitySql += "where area.ParentCode=@AreaCode  or area.Code=@AreaCode ";
            StrCitySql += "order by AreaCode asc ";

            try
            {
                using (var dbCon = ConnectFactory.GetOpenConnection())
                {
                    var paramlist = new DynamicParameters();
                    paramlist.Add("AreaCode", model.AreaCode);
                    paramlist.Add("FillInYear", model.FillInYear);
                    paramlist.Add("ReportStatus", model.Status); 
                    paramlist.Add("CultivarCode", model.itemText); 
                    List<MulAnnualRearStatsModel> list = new List<MulAnnualRearStatsModel>();
                    List<MulAnnualRearStatsModel> listResult = new List<MulAnnualRearStatsModel>();
                    if (model.AreaCode != ProvinceCode)//不为省级用户
                    {
                        list = dbCon.Query<MulAnnualRearStatsModel>(StrAreaSql, paramlist).ToList();
                        foreach (var MulAnnualRear in list)
                        {
                            MulAnnualRear.CultivarName = CultivarName;
                            listResult.Add(MulAnnualRear);
                        }
                        result.model = listResult;
                    }
                    else
                    {
                        list = dbCon.Query<MulAnnualRearStatsModel>(StrCitySql, paramlist).ToList();
                        result.model = list;
                    }
                    //List<MulAnnualRearStatsModel> list2 = new List<MulAnnualRearStatsModel>();
                    //list.Where(s => s.AreaCode == model.AreaCode).FirstOrDefault().AreaName = "合计";
                    //MulAnnualRearStatsModel m = list.Where(s => s.AreaName == "合计").FirstOrDefault();
                    //list.Remove(m);
                    //list2.Add(m);
                    //for (var i = 0; i < list.Count; i++)
                    //{
                    //    list2.Add(list[i]);
                    //}
                    //result.model = list2;
                    if (list != null)
                    {

                        result.status = DefaultKey.SuccessResult;
                        result.message = "获取饲养蚕品种构成统计数据成功！";
                    }
                    else
                    {
                        result.status = DefaultKey.InfoResult;
                        result.message = "获取饲养蚕品种构成统计数据失败！";
                    }
                    dbCon.Dispose();//数据库连接释放
                }
            }
            catch (Exception ex)
            {
                result.status = DefaultKey.ErrorResult;
                result.message = ex.ToString().Trim();
                LogHelper.ErrorLog("获取饲养蚕品种构成统计数据失败", ex);
            }
            return result;
        }
        /// <summary>
        /// 获取时间趋势图数据列表
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public ResResult<List<MulAnnualRearStatsModel>> GetStatsByTimeList(MulNowModel model)
        {
            DictServices dictServices = new DictServices();
            List<Select> listDict = dictServices.GetListByGroupCode("ReportYear").model;
            ResResult<List<MulAnnualRearStatsModel>> result = new ResResult<List<MulAnnualRearStatsModel>>();
            List<MulAnnualRearStatsModel> list = new List<MulAnnualRearStatsModel>();
            if (listDict.Count > 0)
            {
                if (!string.IsNullOrEmpty(model.AreaCode))
                {
                    for (var i = 0; i < listDict.Count; i++)
                    {
                        model.FillInYear = listDict[i].label;
                        List<MulAnnualRearStatsModel> listOne = GetStatsList(model).model;
                        if (listOne.Count > 0)
                        {
                            list.Add(listOne[0]);
                        }
                    }
                    if (list.Count > 0)
                    {
                        result.message = "时间趋势数据列表获取成功";
                        result.model = list.OrderBy(s => s.year).ToList();
                        result.status = DefaultKey.SuccessResult;
                    }
                    else
                    {
                        result.message = "时间趋势数据列表为空";
                        result.status = DefaultKey.InfoResult;
                    }
                }
                else
                {
                    result.message = "时间趋势数据列表失败,当前地区不存在";
                    result.status = DefaultKey.ErrorResult;
                }
            }
            else
            {
                result.message = "时间趋势数据列表失败,时间为空";
                result.status = DefaultKey.ErrorResult;
            }
            return result;
        }
        public ResResult<List<MulAnnualRearStatsModel>> GetDetailStats(MulNowModel model)
        {
            ResResult<List<MulAnnualRearStatsModel>> res = new ResResult<List<MulAnnualRearStatsModel>>();
            List<MulAnnualRearStatsModel> list = new List<MulAnnualRearStatsModel>();
            string ProvinceCode = DefaultKey.ProvinceCode;
            string FillInYear = model.FillInYear;
            try
            {
                if (model.AreaCode == ProvinceCode)
                {
                    var First = GetStatsList(model).model;
                    //First[0].AreaName = "合计";
                    list.Add(First[0]);//省级汇总合计
                    foreach (var item in First)
                    {
                        if (item.AreaCode != ProvinceCode)
                        {
                            MulNowModel model2 = new MulNowModel();
                            model2.FillInYear = FillInYear;
                            model2.AreaCode = item.AreaCode;
                            model2.Status = model.Status;
                            var Second = GetStatsList(model2).model;
                            list.Add(item);
                            foreach (var item2 in Second)
                            {
                                if (model2.AreaCode != item2.AreaCode)
                                {
                                    list.Add(item2);
                                }
                            }
                        }
                    }
                }
                else
                {
                    list = GetStatsList(model).model;//数据获取
                }
            }
            catch (Exception ex)
            {
                res.model = list;
                res.message = "获取统计数据详情失败" + ex.ToString().Trim();
                res.status = DefaultKey.SuccessResult;
            }
            if (list != null)
            {
                res.model = list;
                res.message = "获取统计数据详情成功";
                res.status = DefaultKey.SuccessResult;
            }
            else
            {
                res.message = "获取统计数据详情成失败";
                res.status = DefaultKey.ErrorResult;
            }
            return res;
        }

        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public MemoryStream Method(MulNowModel model)
        {
            model.FillInYear = dict.GetKey(model.FillInYear);
            string ReportId = reportServices.GetReportId(model.ReportCode, model.AreaCode, model.FillInYear);
            FileStream file = null;
            //创建下载Excel文件
            var workbook = new HSSFWorkbook();
            string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
            string filename = @"tempfile\Basic" + DateTime.Now.Ticks.ToString() + ".xls";//临时文件，定期在tempfile手动删除
            string tempExcel = fileIndex + filename;//临时文件路径及全称
            string templateName = fileIndex + @"Excel\Excel.xls";//模板文件
            file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件
            HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
            HSSFSheet sheet = templateBook.GetSheet("MulAnnualRear") as HSSFSheet;//读取模板所在sheet位置
            List<MulAnnualRearEntity> pagelist = GetList(ReportId).model;//数据获取

            HSSFRow row = (HSSFRow)sheet.GetRow(1);//读取模板第二行
            var style = row.GetCell(0).CellStyle;//读取模板第二行第一单元格样式并保存
            row.GetCell(0).CellStyle = style;//对第二行第一单元格设置原来样式

            for (var i = 0; i < pagelist.Count; i++)
            {
                HSSFRow datarow = (HSSFRow)sheet.CreateRow(i + 3);
                var Total = Common.GetInt(Common.GetDecimal(pagelist[i].SeedSizeSpring) + Common.GetDecimal(pagelist[i].SeedSizeSummer) + Common.GetDecimal(pagelist[i].SeedSizeZQ)+ Common.GetDecimal(pagelist[i].SeedSizeWQ));
                datarow.CreateCell(0).SetCellValue(pagelist[i].CultivarName == null ? "" : dict.GetPZName(pagelist[i].CultivarName, "CSCultivar"));
                datarow.CreateCell(1).SetCellValue(Total.ToString());
                datarow.CreateCell(2).SetCellValue(pagelist[i].SeedSizeSpring == null ? "" : Common.GetInt(pagelist[i].SeedSizeSpring));
                datarow.CreateCell(3).SetCellValue(pagelist[i].SeedSizeSummer == null ? "" : Common.GetInt(pagelist[i].SeedSizeSummer));
                datarow.CreateCell(4).SetCellValue(pagelist[i].SeedSizeZQ == null ? "" : Common.GetInt(pagelist[i].SeedSizeZQ));
                datarow.CreateCell(5).SetCellValue(pagelist[i].SeedSizeWQ == null ? "" : Common.GetInt(pagelist[i].SeedSizeWQ));
                datarow.CreateCell(6).SetCellValue(pagelist[i].Remark == null ? "" : pagelist[i].Remark.ToString());
                for (int j = 0; j < 7; j++)
                {
                    datarow.GetCell(j).CellStyle = style;
                }
            }
            sheet.CopyTo(workbook, "Sheet1", true, true);
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                return ms;
            }
        }
        /// <summary>
        /// 统计数据导出
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public MemoryStream MethodStats(MulNowModel model,string TypeName)
        {
            string FillInYear = model.FillInYear;
            AreaServices areaServices = new AreaServices();
            //创建下载Excel文件
            var workbook = new HSSFWorkbook();
            string AreaName = areaServices.GetByCodeModel(model.AreaCode).model.Name == "云南省" ? "云南省_县(市、州)" : areaServices.GetByCodeModel(model.AreaCode).model.Name;//获取当前行政区划名称
            getExcelStatsList(workbook, GetDetailStats(model).model, AreaName, TypeName);//省级汇总(针对曲线)
            if (model.AreaCode == DefaultKey.ProvinceCode)//判断当前用户是否为省级用户
            {
                AreaName = areaServices.GetByCodeModel(model.AreaCode).model.Name;
                model.FillInYear = FillInYear;
                getExcelStatsList(workbook, GetStatsList(model).model, AreaName + "_州市", TypeName);//省级汇总(针对州市)
                var areaList = areaServices.GetPrefectureList();//获取州市级列表
                foreach (var areaCode in areaList)
                {
                    model.AreaCode = areaCode;
                    model.FillInYear = FillInYear;
                    getExcelStatsList(workbook, GetDetailStats(model).model, areaServices.GetByCodeModel(areaCode).model.Name, TypeName);
                }
            }
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                ms.Flush();
                ms.Position = 0;
                return ms;
            }
        }
        /// <summary>
        /// 返回excel工作簿
        /// </summary>
        /// <param name="workbook">工作簿</param>
        /// <param name="sheet">子表</param>
        /// <param name="model"></param>
        /// <param name="AreaName">地区名称</param>
        /// <returns></returns>
        public HSSFWorkbook getExcelStatsList(HSSFWorkbook workbook, List<MulAnnualRearStatsModel> list, string AreaName,string TypeName)
        {
            FileStream file = null;
            string fileIndex = HttpRuntime.AppDomainAppPath.ToString();
            string filename = @"tempfile\Basic" + DateTime.Now.Ticks.ToString() + ".xls";//临时文件，定期在tempfile手动删除
            string tempExcel = fileIndex + filename;//临时文件路径及全称
            string templateName = fileIndex + @"Excel\ExcelStats.xls";//模板文件
            file = new FileStream(templateName, FileMode.Open, FileAccess.Read);//读模板文件
            HSSFWorkbook templateBook = new HSSFWorkbook(file);//读取模板文件信息转换成Excel工作薄
            HSSFSheet sheet = templateBook.GetSheet("MulAnnualRear") as HSSFSheet;//读取模板所在sheet位置
            //List<VegBasicInfoStatsModel> list = new List<VegBasicInfoStatsModel>();
            //list = null;
            //list = GetDetailStats(model).model;
            #region 县市级表格样式
            HSSFRow row = (HSSFRow)sheet.GetRow(1);//读取模板第二行
            var style = row.GetCell(0).CellStyle;//读取模板第二行第一单元格样式并保存
            #endregion
            //row.GetCell(0).CellStyle = style;//对第二行第一单元格设置原来样式
            #region 州市级表格样式
            //var style2 = row.GetCell(1).CellStyle;
            var styleCityInt = Common.GetIntCityCellStyle(templateBook, style);
            var styleAreaInt = Common.GetIntAreaCellStyle(templateBook, style);
            #endregion
            if (list != null)
            {
                for (int i = 0; i < list.Count; i++)
                {
                    HSSFRow datarow = (HSSFRow)sheet.CreateRow(i + 3);
                    datarow.CreateCell(0).SetCellValue(list[i].AreaName == null ? "" : list[i].AreaName.ToString());
                    datarow.CreateCell(1).SetCellValue(list[i].CultivarName==null? TypeName.ToString(): list[i].CultivarName.ToString());
                    datarow.CreateCell(2).SetCellValue(list[i].SeedSizeTotal == null ? 0 :Convert.ToDouble( list[i].SeedSizeTotal));
                    datarow.CreateCell(3).SetCellValue(list[i].SeedSizeSpring == null ? 0 : Convert.ToDouble(list[i].SeedSizeSpring));
                    datarow.CreateCell(4).SetCellValue(list[i].SeedSizeSummer == null ? 0 : Convert.ToDouble(list[i].SeedSizeSummer));
                    datarow.CreateCell(5).SetCellValue(list[i].SeedSizeZQ == null ? 0 : Convert.ToDouble(list[i].SeedSizeZQ));
                    datarow.CreateCell(6).SetCellValue(list[i].SeedSizeWQ == null ? 0 : Convert.ToDouble(list[i].SeedSizeWQ));
                    datarow.CreateCell(7).SetCellValue("");
                    if (CustomFun.IsCity(list[i].AreaCode))
                    {//省级和州市级
                        for (int j = 0; j < 8; j++)
                        {
                            datarow.GetCell(j).CellStyle = styleCityInt;
                        }
                    }
                    else//县级
                    {
                        for (int j = 0; j < 8; j++)
                        {
                            datarow.GetCell(j).CellStyle = styleAreaInt;
                        }
                    }
                }
                sheet.CopyTo(workbook, AreaName, true, true);
            }
            return workbook;
        }
    }
}